<?php
// +----------------------------------------------------------------------
// | CleverPHP [ WE CAN DO IT JUST BeautySoft ]
// +----------------------------------------------------------------------
// | Copyright (c) 2012~2017 http://git.oschina.net/ceiba/CleverPHP All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: ceiba <ceiba_@126.com>
// +----------------------------------------------------------------------

class FileCache{
	public  $cacheDir="temp/static_caches";
	public function setCache(string $key,$caches,$expire=0){
    	$file_name=$_SERVER['DOCUMENT_ROOT'].'/'.$this->cacheDir.'/'.$key.".php";
		if (empty($caches)) {
    		$file_name=str_replace("//", "/", $file_name);
    		@unlink($file_name);
    	}else{
			$content = "<?php\r\n";
    		$content .= "\$data = " . var_export($caches, true) . ";\r\n";
    		$content .= "?>";
			
    		@file_put_contents($file_name, $content, LOCK_EX);
    	}
    
    	return true;
    
    }
	public function getCache(string $cache_name){
    	 static $result = array();
    	 if (!empty($result[$cache_name]))
    	 {
        	return $result[$cache_name];
    	 }
    	$cache_file_path = $_SERVER['DOCUMENT_ROOT'].'/'.$this->cacheDir.'/'.$cache_name.".php";

    	$cache_file_path=str_replace("//", "/", $cache_file_path);
    	if (file_exists($cache_file_path))
    	{
        	include_once($cache_file_path);
        	@$result[$cache_name] = $data;
        	return @$result[$cache_name];
    	}
    	else
    	{
        	return false;
    	}
    
    }
	public function delCache(string $key){
    	return $this->setCache($key,null);
    
    }
    //删除过期缓存
    public function delOverdueCache($lifetime){
    	$expire = time() - $lifetime;
    	$files=$this->get_filenamesbydir("./".$this->cacheDir."/");
    	
    	if ($files){
    		foreach ($files as $key=>$value){
    			if (stripos($value,".php")){
    				$fiel_create_time=@filemtime($value);
    				if ($fiel_create_time<$expire){
    					@unlink($value);
    				}
    					
    			}
    		}
    	}
    	
    }
    
    protected  function get_filenamesbydir($dir){
    	$files =  array();
    	$this->get_allfiles($dir,$files);
    	return $files;
    }
    
    protected function get_allfiles($path,&$files) {
    	if(is_dir($path)){
    		$dp = dir($path);
    		while ($file = $dp ->read()){
    			if($file !="." && $file !=".."){
    				$this->get_allfiles($path."".$file, $files);
    			}
    		}
    		$dp ->close();
    	}
    	if(is_file($path)){
    		$files[] =  $path;
    	}
    }
    


}
?>